from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from urllib.parse import quote
from random import randint
from django.core.cache import cache
from operations.serializers  import WeiboLoginSerializer
from rest_framework import status, permissions
from rest_framework.response import Response
from rest_framework.decorators import permission_classes

def make_state():
    res =  ""
    for i in range(10):
        res += str(randint(0,9))
    return res

@permission_classes([permissions.AllowAny])
class WeiboLoginAsk(GenericViewSet, mixins.CreateModelMixin):
    '''
    微博第三方登录接口，返回一个地址，访问该地址且用户授权后返回token
    '''
    serializer_class = WeiboLoginSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        headers = self.get_success_headers(serializer.data)

        redirect_uri = quote("https://dev.qiusuo-mc.cn/operation-manage/weibo-receive")
        state = make_state()
        cache.set(state, True, 7200)
        client_id = "3064679309"

        authorize_url = "https://api.weibo.com/oauth2/authorize"

        data = {'ask_url': f"{authorize_url}?client_id={client_id}&redirect_uri={redirect_uri}&state={state}"}
        data["success"] = True
        data["code"] = 201

        return Response(data=data, status=status.HTTP_201_CREATED, headers=headers)